from django.conf import settings
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.http import HttpResponse, HttpResponseRedirect, StreamingHttpResponse
from django.shortcuts import redirect, render
from django.template import loader

from .forms import NameForm, UploadFileForm
from .models import Media, Announcement, NativeImage, Score


def signin(request):
    error = '<script>window.alert("账号或者密码错误！");window.location.href="/Fantasy/login/";</script>'

    if request.method == "POST":
        username = request.POST['user']
        password = request.POST['pwd']
        user = authenticate(request, username=username, password=password)
        if user is not None:
            print("登录成功了！")
            login(request, user)
            return redirect("/Fantasy/")
        else:
            return HttpResponse(error)

    return HttpResponse(loader.get_template('Fantasy/login.html').render({}, request))


def index(request):
    form = None
    data = list()

    # 登录验证
    if not request.user.is_authenticated:
        return redirect('%s%s' % (request.path, settings.LOGIN_URL))

    # 搜索验证
    def func(x):
        if message in x.media_name:
            data.append(x)

    if request.method == 'POST':
        form = NameForm(request.POST)
        if form.is_valid():
            message = form.cleaned_data.get('word')

            latest_question_list = Media.objects.all()
            nativeImage = NativeImage.objects.all()
            list(map(func, latest_question_list))
            list(map(func, nativeImage))

            content = {
                'result': data,
            }

            return render(request, "Fantasy/result.html", content)

    # 筛选分类
    first_name = request.user.get_short_name()

    code_software = list()
    zsb = list()
    article = list()
    other = list()

    template = loader.get_template('Fantasy/index.html')
    latest_question_list = Media.objects.all()
    __announcement = Announcement.objects.all()
    __img = NativeImage.objects.all()

    def func(x):
        if x.category == "编程软件":
            code_software.append(x)
        elif x.category == "专升本资料":
            zsb.append(x)
        elif x.category == "精选文章":
            article.append(x)
        else:
            other.append(x)

    list(map(func, latest_question_list))

    content = {
        'form': form,
        'first_name': first_name,
        'img': __img,
        'announcement': __announcement,
        'code_software': code_software,
        'zsb': zsb,
        'article': article,
        'other': other
    }

    return HttpResponse(template.render(content, request))


# 用户注册
def register(request):
    if request.method == "POST":
        try:
            username = request.POST['user']
            password = request.POST['pwd']
            name = request.POST['name']
            # 判断用户名是否存在
            if User.objects.filter(username=username).exists():

                return HttpResponse('<script>window.alert("账号已存在!");</script>')
            else:
                user = User.objects.create_user(username=username, password=password)
                user.first_name = name
                user.groups.add(1)
                user.is_staff = True
                user.save()
                return HttpResponse('<script>window.alert("注册成功！");window.location.href="/Fantasy/login/";</script>')
        except BaseException as error:
            print(error)
            return HttpResponse('注册过程异常，请重新注册！')

    return HttpResponse(loader.get_template('Fantasy/register.html').render({}, request))


def logout_view(request):
    logout(request)
    return HttpResponse(loader.get_template('Fantasy/login.html').render({}, request))


def announcement(request):
    if request.method == 'GET':
        announcement_id = request.GET.get('id')
        __announcement = Announcement.objects.get(pk=announcement_id)
        title = __announcement.title
        content = __announcement.content.split('\n')
        pubdate = __announcement.pub_date
        data = {
            'title': title,
            'content': content,
            'pubdate': pubdate
        }
        return HttpResponse(
            loader.get_template('Fantasy/announce.html').render(data, request))


def handle_uploaded_file(f):
    data = bytes()
    for chunk in f.chunks():
        data += chunk

    print(data.decode())


def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'])
            return HttpResponseRedirect('/Fantasy/')
    else:
        form = UploadFileForm()
    return render(request, 'Fantasy/upload.html', {'form': form})


def score(request):
    if request.method == 'GET':
        data = Score.objects.all()

        content = {
            'data': data
        }
        return render(request, 'Fantasy/score.html', content)


def big_file_download(request):
    """
    大文件下载优化
    """

    def file_iterator(file_name, chunk_size=512):
        with open(file_name) as f:
            while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break

    the_file_name = "big_file.pdf"
    response = StreamingHttpResponse(file_iterator(the_file_name))
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="{0}"'.format(the_file_name)

    return response
